/***************************************************************************
 *   Copyleft 2008-2009 by												   *
 *	 Iwanicki Krzysztof													   *
 *   <gamma.mini.pw.edu.pl/~iwanickik>									   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 ***************************************************************************/
#include "./vTextRenderer.h"
#include <gl/gl.h>

namespace Vendetta {
	vTextRenderer::~vTextRenderer() {
		glDeleteLists(mDisplayList, 256);
	}

	vTextRenderer::vTextRenderer() {
		mDisplayList = 0;
		mTextureID = 0;
	}

	vVoid vTextRenderer::DrawText(vInt iX, vInt iY, const vString& str, const vColor& color, vBool bItalic) {
		glBindTexture(GL_TEXTURE_2D, mTextureID);
		glDisable(GL_DEPTH_TEST);
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		glOrtho(0, mWidth, 0, mHeight, -1, 1);
		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glLoadIdentity();
		glTranslated(iX, iY, 0);
		glListBase(mDisplayList - 32 + (128 * (bItalic ? 1 : 0)));
		glCallLists((vInt) str.Length(), GL_UNSIGNED_BYTE, str.ToConstCharPtr());
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
		glEnable(GL_DEPTH_TEST);
	}

	vVoid vTextRenderer::Resize(vInt iWidth, vInt iHeight) {
		mWidth = iWidth;
		mHeight = iHeight;
	}

	vVoid vTextRenderer::SetTexture(vUInt iTextId) {
		mTextureID = iTextId;
		buildFonts();
	}

	vVoid vTextRenderer::buildFonts() {
		vReal cx;
		vReal cy;

		mDisplayList = glGenLists(256);
		glBindTexture(GL_TEXTURE_2D, mTextureID);

		for (vInt i = 0; i < 256; i++)	{
			cx = vReal (i % 16) / 16.0f;
			cy = vReal (i / 16) / 16.0f;

			glNewList(mDisplayList + i, GL_COMPILE);
			glBegin(GL_QUADS);
			glTexCoord2f(cx, 1 - cy - 0.0625f);
			glVertex2i(0, 0);
			glTexCoord2f(cx + 0.0625f, 1 - cy - 0.0625f);
			glVertex2i(16, 0);
			glTexCoord2f(cx + 0.0625f, 1-cy);
			glVertex2i(16, 16);
			glTexCoord2f(cx, 1-cy);
			glVertex2i(0, 16);
			glEnd();
			glTranslated(10, 0, 0);
			glEndList();
		}	
	}
}